import Cookie from "js-cookie";
export default {
    namespaced: true,//开启命名空间
    state: {
        isCollapse: false,//控制左侧菜单的折叠
        tabList: [
            {
                path: '/',
                name: "home",
                label: "首页",
                icon: "s-home",
                url: "Home/home"
            }
        ],//面包屑
        menu: []

    },
    mutations: {
        // 修改菜单展开收起的方法
        collapseMenu(state) {
            state.isCollapse = !state.isCollapse
        },
        // 更新面包屑数据
        selectMenu(state, payload) {
            // console.log("payload", payload);
            // 判断添加的数据是否为首页
            if (payload.name !== 'home') {
                const index = state.tabList.findIndex(item => item.name === payload.name)
                // 如果不存在
                if (index === -1) {
                    state.tabList.push(payload)
                }

            }

        },
        // 删除指定的tag
        closeTag(state, payload) {
            const index = state.tabList.findIndex(val => val.name === payload.name)
            state.tabList.splice(index, 1)

        },
        // 设置menu数据
        setMenu(state, val) {
            state.menu = val
            // 持久化
            Cookie.set("menu", JSON.stringify(val))
        },
        // 动态注册路由
        addMenu(state, router) {
            // 判断缓冲中是否有数据
            if (!Cookie.get("menu")) return;
            const menu = JSON.parse(Cookie.get("menu"))
            state.menu = menu;
            // 组装动态路由的数据
            const menuArray = []
            menu.forEach(item => {
                if (item.children) {
                    item.children = item.children.map(item => {
                        item.component = () => import(`../../views/${item.url}`)
                        return item
                    })
                    menuArray.push(...item.children)
                } else {
                    item.component = () => import(`../../views/${item.url}`)
                    menuArray.push(item)
                }
            });
            // 路由的动态添加
            menuArray.forEach(item => {
                router.addRoute("main", item)
            })

        }
    }
}